package com.compass.doctor.ui.mine

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import androidx.activity.viewModels
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.databinding.ActivityQrCodeBinding
import com.compass.doctor.ui.mine.viewmodel.MineViewModel
import com.compass.doctor.utils.ImageUtil
import com.compass.framework.constant.WX_APPID
import com.compass.framework.ext.onClick
import com.compass.framework.glide.setUrl
import com.compass.framework.glide.setUrlCircle
import com.compass.framework.helper.CompassAppHelper
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.model.User
import com.compass.framework.utils.StatusBarSettingHelper
import com.compass.framework.utils.ViewUtils.getDownscaledBitmapForView
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXImageObject
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import java.io.File
import java.io.FileOutputStream


/**
 * Description： 我的二维码
 * Date:2023/12/21 13:37
 */
class QRCodeActivity : BaseVBActivity<ActivityQrCodeBinding>() {

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, QRCodeActivity::class.java)
            context.startActivity(intent)
        }
    }

    private val mineViewModel: MineViewModel by viewModels()
    private lateinit var api: IWXAPI
    override fun initView(savedInstanceState: Bundle?) {
        StatusBarSettingHelper.setStatusBarTranslucent(this)
        StatusBarSettingHelper.statusBarLightMode(this@QRCodeActivity, true)
        api = WXAPIFactory.createWXAPI(this, WX_APPID, true)
        api.registerApp(WX_APPID)
        val user = UserInfoManager.getUserInfo()
        user?.let {
            setUserInfo(it)
            var version = if (CompassAppHelper.isDebug()) "develop" else "release"
//            var version = if (CompassAppHelper.isDebug()) "develop" else "develop"
            mineViewModel.getHomePageQRCode(it.id, version)

        }
    }

    override fun intListener() {
        mBinding.tvSave.onClick {

            getDownscaledBitmapForView(mBinding.clyCode, 0.8f)?.let { bitmap ->
                saveBitmapToAlbum(
                    bitmap
                )
            }
        }
        mBinding.tvShare.onClick {
            getDownscaledBitmapForView(mBinding.clyCode, 0.8f)?.let { bitmap ->
                sharePicture(bitmap, 0)
            }
        }
    }

    override fun initData() {

        mineViewModel.codeLiveData.observe(this) {
            mBinding.imgCode.setUrl(it?.qrCode)
        }
    }

    private fun setUserInfo(user: User) {
        mBinding.apply {
            doctorName.text = user.name
            ivHead.setUrlCircle(user.avatar)
            hospitalName.text = user.hospitalName
            departmentName.text = user.departmentName
        }
    }


    /**
     * 保存bitmap到相册
     */
    private fun saveBitmapToAlbum(bitmap: Bitmap) {
        val appDir = File(externalCacheDir, "image")
        if (!appDir.exists()) {
            appDir.mkdir()
        }
        val fileName = "IMG_${System.currentTimeMillis()}.jpg"
        val file = File(appDir, fileName)
        try {
            val fos = FileOutputStream(file)
            fos.use { fos ->
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos)
                fos.flush()
                fos.close()
            }
            //把文件插入到系统相册
            MediaStore.Images.Media.insertImage(contentResolver, file.absolutePath, fileName, null)

            //通知图库更新
            sendBroadcast(
                Intent(
                    Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                    Uri.fromFile(File(file.path))
                )
            )
            showToast("保存成功")
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private val SIZE = 150
    private fun sharePicture(bitmap: Bitmap, shareType: Int) {
        var imgObj = WXImageObject(bitmap)
        var msg = WXMediaMessage()
        msg.mediaObject = imgObj

        //设置缩略图
        var thumbBitmap = Bitmap.createScaledBitmap(bitmap, SIZE, SIZE, true)
        bitmap.recycle()
        msg.thumbData = ImageUtil.bmpToByteArray(thumbBitmap, true)

        //构造一个Req
        val req = SendMessageToWX.Req()
        req.transaction = buildTransaction("doctorImg")
        req.message = msg
        req.scene = shareType
        //调用api接口，发送数据到微信
        api.sendReq(req)

    }

    private fun buildTransaction(type: String): String {
        return "${type}${System.currentTimeMillis()}"
    }
}